
#include "dd_spline2.h"
#include <cassert>

#include "util/mmgr.h"		// Needs to come in early

using namespace dd;

Spline2::Spline2()
{

}

Spline2::~Spline2()
{

}

void Spline2::Render(DBG_BUFFER_2D* _pBuffer)
{
	if (!m_pSpline) return;
	math::Vec2 PV1, PV2, PV3, PV4;
	math::Vec2 From, To;
	float s;
	float inv_segments = 1.0f / float(m_pSpline->GetDrawSegments());
	unsigned int NodeC = (unsigned int)m_pSpline->GetNodeC();

	if (NodeC < 2) return;

	for (unsigned int i = 0; i < (NodeC - 1); i++)
	{
		if (i == 0)
			PV1 = m_pSpline->GetNode(i)->Pos;
		else
			PV1 = m_pSpline->GetNode(i-1)->Pos;

		PV2 = m_pSpline->GetNode(i)->Pos;
		PV3 = m_pSpline->GetNode(i+1)->Pos;

		if ((i + 2) >= NodeC)
			PV4 = PV3;
		else
			PV4 = m_pSpline->GetNode(i+2)->Pos;

		s = 0.0f;
		From = PV2;

		for (int j = 0; j < (int)m_pSpline->GetDrawSegments(); j++)
		{
			s = float(j+1) * inv_segments;
			m_pSpline->Interpolate(To, PV1, PV2, PV3, PV4, s);
			AddLine(_pBuffer, From-m_Offset, To-m_Offset, m_Color);
			From = To;
		}
	}
	/*int				Steps = m_pSpline->GetCacheSize();
	math::Vec2		From  = m_pSpline->GetCachePos(0);
	for (int i=1; i<Steps; i+=10)
	{
		math::Vec2 To = m_pSpline->GetCachePos(i);
		AddLine(_pBuffer, From-m_Offset, To-m_Offset, m_Color);
		From = To;
	}
	unsigned int NodeC = (unsigned int)m_pSpline->GetNodeC();
	if (NodeC < 2) return;*/
	if (m_Knots)
	{
		for (unsigned int i = 0; i < NodeC; i++)
		{
			math::Vec2	Pos = m_pSpline->GetNode(i)->Pos - m_Offset;
			math::Vec2	NodeX(5.0f/800.0f, 0);
			math::Vec2	NodeY(0, 5.0f/600.0f);
			AddLine(_pBuffer, Pos - (NodeX + NodeY), (Pos + NodeX) - NodeY, m_Color);
			AddLine(_pBuffer, (Pos + NodeX) - NodeY, (Pos + NodeX) + NodeY, m_Color);
			AddLine(_pBuffer, (Pos + NodeX) + NodeY, Pos + NodeY - NodeX, m_Color);
			AddLine(_pBuffer, Pos + NodeY - NodeX, Pos - (NodeX + NodeY), m_Color);
		}
	}
}

void Spline2::Setup(math::SplineCache2D* _pSpline, float _dT, COLOR _Color, bool _Knots, const math::Vec2& Offset )
{
	m_Knots		= _Knots;
	m_Color		= _Color;
	m_pSpline	= _pSpline;
	m_dT		= _dT;
	m_Offset	= Offset ;
}
